import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Table, Button, Modal, Form, Input, Select, Space, message, Popconfirm, TreeSelect } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { TableColumnsType } from 'antd';

const { Option } = Select;

interface MenuData {
  key: number;
  id: number;
  name: string;
  path: string;
  component: string;
  parentId: number | null;
  icon: string;
  sort: number;
  type: 'menu' | 'button';
  permission: string;
  status: 'enabled' | 'disabled';
  children?: MenuData[];
}

// 菜单类型选项 - 移至组件外部避免重复创建
const menuTypes = [
  { label: '菜单', value: 'menu' },
  { label: '按钮', value: 'button' },
];

// 状态选项 - 移至组件外部避免重复创建
const statusOptions = [
  { label: '启用', value: 'enabled' },
  { label: '禁用', value: 'disabled' },
];

const MenuManagement: React.FC = () => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState<MenuData[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingMenu, setEditingMenu] = useState<MenuData | null>(null);

  // 使用useCallback优化fetchMenus函数
  const fetchMenus = useCallback(async () => {
    setLoading(true);
    try {
      // 模拟API调用 - 使用缓存避免频繁重复创建对象
      const mockMenusFromCache = sessionStorage.getItem('mockMenus');
      
      if (mockMenusFromCache) {
        // 使用缓存数据
        setDataSource(JSON.parse(mockMenusFromCache));
        setLoading(false);
        return;
      }
      
      // 如果没有缓存，创建模拟数据
      setTimeout(() => {
        const mockMenus: MenuData[] = [
          {
            key: 1,
            id: 1,
            name: '系统管理',
            path: '/system',
            component: 'Layout',
            parentId: null,
            icon: 'SettingOutlined',
            sort: 1,
            type: 'menu',
            permission: '',
            status: 'enabled',
            children: [
              {
                key: 2,
                id: 2,
                name: '用户管理',
                path: '/system/user',
                component: 'system/user/index',
                parentId: 1,
                icon: 'UserOutlined',
                sort: 1,
                type: 'menu',
                permission: 'system:user:list',
                status: 'enabled',
                children: [
                  {
                    key: 6,
                    id: 6,
                    name: '新增用户',
                    path: '',
                    component: '',
                    parentId: 2,
                    icon: '',
                    sort: 1,
                    type: 'button',
                    permission: 'system:user:add',
                    status: 'enabled',
                  },
                  {
                    key: 7,
                    id: 7,
                    name: '编辑用户',
                    path: '',
                    component: '',
                    parentId: 2,
                    icon: '',
                    sort: 2,
                    type: 'button',
                    permission: 'system:user:edit',
                    status: 'enabled',
                  },
                ]
              },
              {
                key: 3,
                id: 3,
                name: '角色管理',
                path: '/system/role',
                component: 'system/role/index',
                parentId: 1,
                icon: 'TeamOutlined',
                sort: 2,
                type: 'menu',
                permission: 'system:role:list',
                status: 'enabled',
              },
              {
                key: 4,
                id: 4,
                name: '菜单管理',
                path: '/system/menu',
                component: 'system/menu/index',
                parentId: 1,
                icon: 'MenuOutlined',
                sort: 3,
                type: 'menu',
                permission: 'system:menu:list',
                status: 'enabled',
              },
            ],
          },
          {
            key: 5,
            id: 5,
            name: '内容管理',
            path: '/content',
            component: 'Layout',
            parentId: null,
            icon: 'FileTextOutlined',
            sort: 2,
            type: 'menu',
            permission: '',
            status: 'enabled',
          },
        ];
        
        // 缓存数据到sessionStorage避免重复创建
        sessionStorage.setItem('mockMenus', JSON.stringify(mockMenus));
        
        setDataSource(mockMenus);
        setLoading(false);
      }, 300); // 减少模拟延迟时间
    } catch (error) {
      console.error('获取菜单列表失败', error);
      message.error('获取菜单列表失败');
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchMenus();
  }, [fetchMenus]);

  // 使用useMemo优化树形数据构建
  const buildTreeSelectData = useCallback((menus: MenuData[], parentName = ''): any[] => {
    return menus.map(menu => {
      const newTitle = parentName ? `${parentName} / ${menu.name}` : menu.name;
      const item = {
        title: newTitle,
        value: menu.id,
        disabled: menu.type === 'button',
      };

      if (menu.children && menu.children.length > 0) {
        const children = buildTreeSelectData(menu.children, newTitle);
        return { ...item, children };
      }

      return item;
    });
  }, []);

  // 使用useMemo缓存树选择数据
  const treeSelectData = useMemo(() => buildTreeSelectData(dataSource), [dataSource, buildTreeSelectData]);

  const handleAdd = useCallback(() => {
    form.resetFields();
    form.setFieldsValue({
      type: 'menu',
      status: 'enabled',
      sort: 1,
      parentId: null,
    });
    setEditingMenu(null);
    setModalVisible(true);
  }, [form]);

  const handleEdit = useCallback((record: MenuData) => {
    setEditingMenu(record);
    form.setFieldsValue({
      name: record.name,
      path: record.path,
      component: record.component,
      parentId: record.parentId,
      icon: record.icon,
      sort: record.sort,
      type: record.type,
      permission: record.permission,
      status: record.status,
    });
    setModalVisible(true);
  }, [form]);

  // 使用useCallback优化删除处理函数
  const handleDelete = useCallback((id: number) => {
    // 递归检查菜单项及其子项
    const hasChildrenMenu = (menu: MenuData, targetId: number): boolean => {
      if (menu.id === targetId) return true;
      if (menu.children && menu.children.length > 0) {
        return menu.children.some(child => hasChildrenMenu(child, targetId));
      }
      return false;
    };

    // 递归删除菜单项及其子项
    const deleteMenu = (menus: MenuData[], targetId: number): MenuData[] => {
      return menus
        .filter(menu => menu.id !== targetId)
        .map(menu => {
          if (menu.children && menu.children.length > 0) {
            return {
              ...menu,
              children: deleteMenu(menu.children, targetId),
            };
          }
          return menu;
        });
    };

    // 检查是否存在子菜单
    const hasChildren = dataSource.some(menu => {
      if (menu.id === id) {
        return menu.children && menu.children.length > 0;
      }
      if (menu.children && menu.children.length > 0) {
        return menu.children.some(subMenu => hasChildrenMenu(subMenu, id));
      }
      return false;
    });

    if (hasChildren) {
      message.error('该菜单下存在子菜单，无法删除');
      return;
    }

    // 执行删除操作
    const newDataSource = deleteMenu(dataSource, id);
    setDataSource(newDataSource);
    // 更新缓存
    sessionStorage.setItem('mockMenus', JSON.stringify(newDataSource));
    message.success('删除成功');
  }, [dataSource]);

  // 使用useCallback优化保存处理函数
  const handleSave = useCallback(async () => {
    try {
      const values = await form.validateFields();
      
      const newMenu: MenuData = {
        key: editingMenu ? editingMenu.id : Date.now(),
        id: editingMenu ? editingMenu.id : Date.now(),
        name: values.name,
        path: values.path || '',
        component: values.component || '',
        parentId: values.parentId,
        icon: values.icon || '',
        sort: values.sort,
        type: values.type,
        permission: values.permission || '',
        status: values.status,
      };

      // 递归查找并更新或添加菜单项
      const updateOrAddMenu = (menus: MenuData[], newMenu: MenuData, isUpdate = false): MenuData[] => {
        if (!isUpdate) {
          // 如果是添加新菜单且没有父菜单，直接添加到根菜单
          if (newMenu.parentId === null) {
            return [...menus, newMenu];
          }
          
          // 递归查找父菜单并添加
          return menus.map(menu => {
            if (menu.id === newMenu.parentId) {
              // 找到父菜单，添加到子菜单中
              const children = menu.children || [];
              return { ...menu, children: [...children, newMenu] };
            }
            // 继续查找子菜单
            if (menu.children && menu.children.length > 0) {
              return { ...menu, children: updateOrAddMenu(menu.children, newMenu) };
            }
            return menu;
          });
        } else {
          // 更新现有菜单
          return menus.map(menu => {
            if (menu.id === newMenu.id) {
              // 保留原有的children
              const children = menu.children || [];
              return { ...newMenu, children };
            }
            // 继续查找子菜单
            if (menu.children && menu.children.length > 0) {
              return { ...menu, children: updateOrAddMenu(menu.children, newMenu, true) };
            }
            return menu;
          });
        }
      };

      const updatedDataSource = updateOrAddMenu(dataSource, newMenu, !!editingMenu);
      setDataSource(updatedDataSource);
      // 更新缓存
      sessionStorage.setItem('mockMenus', JSON.stringify(updatedDataSource));
      setModalVisible(false);
      message.success(editingMenu ? '更新成功' : '添加成功');
    } catch (error) {
      console.error('表单验证失败', error);
    }
  }, [form, editingMenu, dataSource]);

  // 使用useMemo优化表格列配置
  const columns: TableColumnsType<MenuData> = useMemo(() => [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
      width: 180,
    },
    {
      title: '组件',
      dataIndex: 'component',
      key: 'component',
      width: 180,
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
      width: 100,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 80,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 80,
      render: (type: string) => type === 'menu' ? '菜单' : '按钮',
    },
    {
      title: '权限标识',
      dataIndex: 'permission',
      key: 'permission',
      width: 200,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string) => (
        <span className={status === 'enabled' ? 'text-green-500' : 'text-red-500'}>
          {status === 'enabled' ? '启用' : '禁用'}
        </span>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record: MenuData) => (
        <Space size="middle">
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此菜单吗?"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ], [handleDelete, handleEdit]);

  // 使用useMemo优化表格配置
  const tableConfig = useMemo(() => ({
    columns,
    dataSource,
    loading,
    rowKey: "id",
    pagination: false,
    expandable: {
      defaultExpandAllRows: true,
    },
    scroll: { x: 1300 }, // 启用水平滚动
  }), [columns, dataSource, loading]);

    return (
    <div className="bg-white p-6 rounded-lg shadow">
      <div className="mb-4">
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          新增菜单
        </Button>
      </div>
      
      <Table {...tableConfig} />

      <Modal
        title={editingMenu ? '编辑菜单' : '新增菜单'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => setModalVisible(false)}
        maskClosable={false}
        width={650}
        destroyOnClose // 关闭时销毁Modal内容
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            type: 'menu',
            status: 'enabled',
            sort: 1,
            parentId: null,
          }}
        >
          <Form.Item
            name="parentId"
            label="上级菜单"
          >
            <TreeSelect
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={treeSelectData}
              placeholder="请选择上级菜单"
              treeDefaultExpandAll
              allowClear
            />
          </Form.Item>
          
          <Form.Item
            name="type"
            label="菜单类型"
            rules={[{ required: true, message: '请选择菜单类型' }]}
          >
            <Select>
              {menuTypes.map(type => (
                <Option key={type.value} value={type.value}>{type.label}</Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="name"
            label="菜单名称"
            rules={[{ required: true, message: '请输入菜单名称' }]}
          >
            <Input placeholder="请输入菜单名称" />
          </Form.Item>
          
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.type !== currentValues.type}
          >
            {({ getFieldValue }) => (
              getFieldValue('type') === 'menu' ? (
                <>
                  <Form.Item
                    name="path"
                    label="路由路径"
                    rules={[{ required: true, message: '请输入路由路径' }]}
                  >
                    <Input placeholder="请输入路由路径" />
                  </Form.Item>
                  
                  <Form.Item
                    name="component"
                    label="组件路径"
                    rules={[{ required: true, message: '请输入组件路径' }]}
                  >
                    <Input placeholder="请输入组件路径" />
                  </Form.Item>
                  
                  <Form.Item
                    name="icon"
                    label="图标"
                  >
                    <Input placeholder="请输入图标名称" />
                  </Form.Item>
                </>
              ) : null
            )}
          </Form.Item>
          
          <Form.Item
            name="permission"
            label="权限标识"
          >
            <Input placeholder="请输入权限标识" />
          </Form.Item>
          
          <Form.Item
            name="sort"
            label="显示排序"
            rules={[{ required: true, message: '请输入显示排序' }]}
          >
            <Input type="number" placeholder="请输入显示排序" />
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              {statusOptions.map(status => (
                <Option key={status.value} value={status.value}>{status.label}</Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
        </div>
  );
};

export default React.memo(MenuManagement);
